<template>
  <div class="input-box">
    <input
      type="text"
      style="display: block; width: 100%; border: none;background:#fff"
      dateType="1"
      v-model="state.name"
      :placeholder="prop.placeholder"
      @focus="onFocus($event)"
      @blur="onBlur"
      @input="updateValue"
    />
    <div class="input-main" v-if="isMain && dataListMain.length">
      <div class="input-main-box">
        <div class="input-item" v-for="item in dataListMain" :key="item.id">
          <h5 dateType="2" @click.stop="updateSelectValue($event, item)">
            {{ item.name }}
          </h5>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { onMounted } from "vue";
import { reactive } from "vue";
import { ref } from "vue";
const prop = defineProps({
  dataList: {
    type: Array,
    default: () => [],
  },
  placeholder: {
    type: String,
    default: "",
  },
  curType: {
    type: String,
    default: "",
  },
});

const emits = defineEmits(["update:updateValue"]);

const state = reactive({
  id: "",
  name: "",
});

const isMain = ref(false);
const curTypeIndex = ref();
const dataListMain = ref([]);

onMounted(() => {
  curTypeIndex.value = prop.curType;
  dataListMain.value = prop.dataList;
  document.addEventListener("click", function (e) {
    if (curTypeIndex.value == 0) {
      isMain.value = true;
    } else {
      isMain.value = false;
    }
    if (!e.target.attributes.datetype) {
      isMain.value = false;
    }
  });
});

const onFocus = (ev) => {
  curTypeIndex.value = 0;
  dataListMain.value = prop.dataList.filter(
    (o) => o.name.indexOf(state.name) > -1
  );
  isMain.value = !isMain.value;
};

const onBlur = (ev) => {
  curTypeIndex.value = prop.curType;
};

const updateValue = () => {
  state.id = "";
  dataListMain.value = prop.dataList.filter(
    (o) => o.name.indexOf(state.name) > -1
  );
  emits("update:updateValue", state);
};

const updateSelectValue = (ev, item) => {
  console.log(item, "item");
  state.id = item.id;
  state.name = item.name;
  emits("update:updateValue", state);
  isMain.value = false;
  ev.preventDefault();
};
</script>


<style lang="scss" scoped>
.input-box {
  position: relative;
  width: 100%;

  .input-main {
    position: absolute;
    bottom: 0;
    transform: translateY(100%);
    background: #fff;
    z-index: 9;
    width: 100%;
    border: 1px solid #e2e2e2;
    box-sizing: border-box;
    margin-top: 1em;
    .input-main-box {
      position: relative;
      max-height: 8em;
      overflow: auto;
      .close-btn {
        position: absolute;
        top: 0.5em;
        right: 0.5em;
      }
    }

    .input-item {
      border-bottom: 1px solid #e2e2e2;
      padding: 0 0.5em;
      line-height: 2.8;
    }

    .input-item:last-child {
      border: none;
    }
  }
}
.empty-box {
  padding: 1em;
  text-align: center;
}
</style>
